#导入类视图
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views import View
import json
# 导入数据库
from myapp.models import User

import requests

from django.shortcuts import render, redirect

from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入时间模块
import time
import base64
import hmac
import hashlib
from hashlib import sha256
import urllib


#md5加密方法
def make_password(mypass):

	#生成md5对象
	md5 = hashlib.md5()
	#定义机密对象
	sign_str = str(mypass)
	#转码
	sign_utf8 = sign_str.encode(encoding="utf-8")
	#加密
	md5.update(sign_utf8)
	#生成密钥串
	md5_server = md5.hexdigest()

	return md5_server


# 钉钉
def kaoding_back(request):
    #获取code
    code = request.GET.get("code")

    t = time.time()

    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'fp3nkGoIhS2Mi9EdVql_nKXg6Y0-HSGp-2F_p7IAv_Quc56yhhrinpqbcQRg3RqF'

    # 构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode(
    	'utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())

    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode(
    	"utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoahmelrgy51wltnjzs", data=json.dumps(payload), headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)
    # return HttpResponse(res.text)

    # 判断是否为第一次钉钉登录
    user = User.objects.filter(username=str(
        res_dict['user_info']['nick'])).first()

    ding_id = ''
    user_id = ''

    if user:
        # 代表曾经用过钉钉登录
        ding_id = user.username
        user_id = user.id

    else:
        # 代表首次登录，入库
        user = User(username=str(res_dict['user_info']['nick']), password='')
        # 保存入库
        user.save()

        # 查询用户id
        user = User.objects.filter(username=str(
            res_dict['user_info']['nick'])).first()
        ding_id = str(res_dict['user_info']['nick'])
        user_id = user.id
    # 进行跳转
    return HttpResponse("登陆成功")





# 登录
class KaoLogin(APIView):

	def get(self, request):
		# 获取用户名
		username = request.GET.get('username', 'null')
		# 获取密码
		password = request.GET.get('password', 'null')

		# 验证信息是否正确
		user = User.objects.filter(
		    username=username, password=make_password(password)).first()

		# 如果信息正确
		if user:
			res = {}
			res['code'] = 200
			res['message'] = "登陆成功"
			res['username'] = user.username
			res['uid'] = user.id
			return Response(res)

		# 如果错误
		res = {}
		res['code'] = 401
		res['message'] = "信息错误"
		return Response(res)


#注册模块
class KaoRegister(APIView):

	def get(self, request):

		#接收参数  dict['username']
		username = request.GET.get('username', 'null')
		password = request.GET.get('password', 'null')

		print(username)
		print(password)


		#排重
		user = User.objects.filter(username=username).first()

		if user:
			res = {}
			res['code'] = 405
			res['message'] = '该用户名已存在'
			return Response(res)

		#入库
		user = User(username=username, password=make_password(password))
		user.save()

		res = {}
		res['code'] = 200
		res['message'] = '恭喜，注册成功'

		return Response(res)
